(function () {
    'use strict';

    var md = angular.module('imageFiter', []);
    md.directive('imageFiter', imageViewer);

    imageViewer.$inject = ['$window', '$document', '$timeout'];
    function imageViewer($window, $document, $timeout) {
        // Usage:
        //
        // Creates:
        //
        var directive = {
            link: link,
            restrict: 'A',
            scope: {
                imageFiter:'=imageFiter'
            }
        };
        return directive;

        function link(scope, element, attrs) {
            var parent = element.parent();
            var parentHeight = parent.height();
            var imgWidth, imgHeight;


            function fit() {
                $timeout(function () {
                    imgWidth = element[0].naturalWidth;
                    imgHeight = element[0].naturalHeight;
                    console.log(imgWidth+'-'+imgHeight)
                    var fit = parentHeight - 40 + 'px';
                    if (imgWidth > imgHeight) {
                        console.log('width')
                        element.css('width', fit);
                        element.css('height', 'auto');
                    }
                    else {

                        element.css('width', 'auto');
                        element.css('height', fit);
                    }
                }, 0);
            }

            var rotate = 0;
            var rotateBtn = angular.element('<div title="旋转" class="pos-abt wrapper" style="z-index: 999;top:10px;right: 20px;cursor: pointer"><i class="fa fa-repeat fa-2x"></i></div>');
            rotateBtn.bind('click', function () {
                rotate += 90;
                element.css('transform', 'rotate(' + rotate + 'deg)');
                if (rotate == 360) {
                    rotate = 0;
                }
            })
            parent.append(rotateBtn);

            scope.$watch('imageFiter', function () {
                
                fit();
            })
        }
    }

})();